package cn.sfrog.project.biz.admin.utils.tencentlive;

import cn.sfrog.project.biz.admin.tencent.TencentLiveApiService;
import cn.sfrog.project.biz.web.vo.room.LiveAddressVO;
import com.tencentcloudapi.common.AbstractModel;
import com.tencentcloudapi.common.CommonClient;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.live.v20180801.LiveClient;
import com.tencentcloudapi.live.v20180801.models.DescribeLiveStreamOnlineListRequest;
import com.tencentcloudapi.live.v20180801.models.DescribeLiveStreamOnlineListResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import javax.crypto.SecretKey;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.*;
import java.util.Random;

/**
 * @Author chenl
 * @Date 2024-05-23 13:42
 * @title LiveUtils
 * @description
 **/
public class LiveUtils {
    private static Logger log = LoggerFactory.getLogger(LiveUtils.class);

    //--------------------------------------------------生成流地址（开始）--------------------------------

    private static final char[] DIGITS_LOWER =
            {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

//
////    @Value("")
//
//    private static final String secretId = "AKIDlSEweHovGbySEACOiEwdFkN6nPvLgv6P";//腾讯云 访问密钥 secretId
//    private static final String secretKey = "eFwZp5CFBwc9c4Qj0GUjrskUtLwTsQvE";//腾讯云 访问密钥 secretKey
//
//    private static final String pushKey = "bafe1de15ac5713fa1b20a16835cd5e2"; //域名管理中点击推流域名-->推流配置-->鉴权配置-->主KEY
//    private static final String pullKey = "BbHDWmicaeaSDcfxcc7Q"; //域名管理中点击推流域名-->推流配置-->鉴权配置-->主KEY
//    private static final String pushDomain = "peiyi-live-push.peiyiyiliao.com"; //云直播控制台配置的推流域名
//    private static final String pullDomain = "peiyi-live-play.peiyiyiliao.com";//云直播控制台配置的播放域名
//    private static final String appName = "/live/"; //app应用名称
//
//    /**
//     * 下面是即时通讯IM相关配置
//     */
//    public static final String imSDKAppID = "1600037750"; //即时通讯im-->应用管理-->应用 SDKAppID，可在即时通信 IM 控制台 的应用卡片中获取。
//    public static final String imSecretKey = "902a9d742992d3f5df7175dd28abc453173fc0e3090ae1f0682ba6f6b63ffe42"; //即时通讯im-->应用管理-->应用 密钥，可在即时通信 IM 控制台 的应用卡片中获取。


    public static void main(String[] args) {


//        TLSSigAPIv2 api = new TLSSigAPIv2(1600037750, "902a9d742992d3f5df7175dd28abc453173fc0e3090ae1f0682ba6f6b63ffe42");
//        System.out.print(api.genUserSig("123", 180 * 86400));

//        try {
//            // 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
//            // 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议采用更安全的方式来使用密钥，请参见：https://cloud.tencent.com/document/product/1278/85305
//            // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
//            Credential cred = new Credential(secretId, secretKey);
//            // 实例化一个http选项，可选的，没有特殊需求可以跳过
//            HttpProfile httpProfile = new HttpProfile();
//            httpProfile.setEndpoint("live.tencentcloudapi.com");
//            // 实例化一个client选项，可选的，没有特殊需求可以跳过
//            ClientProfile clientProfile = new ClientProfile();
//            clientProfile.setHttpProfile(httpProfile);
//            // 实例化要请求产品的client对象,clientProfile是可选的
//            LiveClient client = new LiveClient(cred, "", clientProfile);
//            // 实例化一个请求对象,每个接口都会对应一个request对象
//            DescribeLiveStreamOnlineListRequest req = new DescribeLiveStreamOnlineListRequest();
//
//            // 返回的resp是一个DescribeLiveStreamOnlineListResponse的实例，与请求对象对应
//            DescribeLiveStreamOnlineListResponse resp = client.DescribeLiveStreamOnlineList(req);
//            // 输出json格式的字符串回包
//            System.out.println(AbstractModel.toJsonString(resp));
//        } catch (TencentCloudSDKException e) {
//            System.out.println(e.toString());
//        }

    }

    /**
     * 过期时间戳
     *
     * @param localDateTime 默认当前时间
     * @return
     */
    public static long getTxTime(LocalDateTime localDateTime) {
        //这里对当前时间+1天过期时间处理
        long nowTime = localDateTime.toEpochSecond(ZoneOffset.of("+8"));
        return nowTime + 60 * 60 * 24;
    }


    /*
     * KEY+ streamName + txTime
     */
    public static String getSafeUrl(String key, String streamName, long txTime) {

        String input = new StringBuilder().
                append(key).
                append(streamName).
                append(Long.toHexString(txTime).toUpperCase()).toString();


        String txSecret = null;
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            txSecret = byteArrayToHexString(
                    messageDigest.digest(input.getBytes("UTF-8")));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }


        return txSecret == null ? "" :
                new StringBuilder().
                        append("txSecret=").
                        append(txSecret).
                        append("&").
                        append("txTime=").
                        append(Long.toHexString(txTime).toUpperCase()).
                        toString();
    }


    private static String byteArrayToHexString(byte[] data) {
        char[] out = new char[data.length << 1];


        for (int i = 0, j = 0; i < data.length; i++) {
            out[j++] = DIGITS_LOWER[(0xF0 & data[i]) >>> 4];
            out[j++] = DIGITS_LOWER[0x0F & data[i]];
        }
        return new String(out);
    }

    public static String genUsersig(String userId, String imSDKAppID, String imSecretKey) {
        TLSSigAPIv2 tlsSigAPIv2 = new TLSSigAPIv2(Long.parseLong(imSDKAppID), imSecretKey);
        return tlsSigAPIv2.genUserSig(userId, 180 * 86400);
    }

    /**
     * 构造腾讯im 请求url
     *
     * @param imDomain
     * @param userId
     * @param imSDKAppID
     * @param imSecretKey
     * @return
     */
    public static String buildImRequestUrl(String imDomain, String imApi, String userId, String imSDKAppID, String imSecretKey) {
        /**
         * 示例
         * /v4/group_open_http_svc/get_appid_group_list?usersig=xxx&identifier=admin&sdkappid=88888888&random=99999999&contenttype=json HTTP/1.1
         */

        String usersig = genUsersig(userId, imSDKAppID, imSecretKey);

        String sb = new StringBuilder()
                .append(imDomain)
                .append(imApi)
                .append("?sdkappid=")
                .append(imSDKAppID)
                .append("&identifier=")
                .append(userId)
                .append("&usersig=")
                .append(usersig)
                .append("&random=")
                .append(genRandomUnsignedInt())
                .append("&contenttype=json")
                .toString();


        return sb;
    }



    private static String genRandomUnsignedInt() {
        Random random = new Random();
        int unsignedInt = random.nextInt();  // 生成一个有符号的随机整数
        unsignedInt &= 0xFFFFFFFF;           // 转换为无符号整数
        return String.valueOf(unsignedInt);
    }

}
